const fs = require('fs');
const path = require('path');

const entry = 'pages';
const directory = path.resolve(__dirname, './src/' + entry);
const pagesObject = {};
let getEntry = null;
(getEntry = (dir) => {
  const entryArr = fs.readdirSync(dir);
  let pathName, filePath;

  entryArr.forEach(function (filename) {
    filePath = dir + '/' + filename;
    if (fs.statSync(filePath).isDirectory()) {
      getEntry(filePath);
    } else {
      if (filename.endsWith('.js')) {
        // 不能以 / 开头，所以 + 1
        let sindex = filePath.indexOf(entry) + entry.length + 1;
        pathName = filePath.substring(sindex, filePath.lastIndexOf('.'));
        pagesObject[pathName] = {
          // entry for the page
          entry: filePath,
          // the source template
          template: 'public/index.html',
          // output as dist/index.html
          filename: pathName + '.html',
          // when using title option,
          // template title tag needs to be <title><%= htmlWebpackPlugin.options.title %></title>
          // chunks to include on this page, by default includes
          // extracted common chunks and vendor chunks.
          chunks: ['chunk-vendors', 'chunk-common', pathName]
        }
      }
    }
  })
})(directory)

module.exports = pagesObject;
